﻿using IOA.MES.Business;
using IOA.MES.DataAccess.Enum;
using IOA.MES.DataAccess.VModel;
using IOA.Utils;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Mvc;

namespace IOA.MES.Web.Controllers
{
    /// <summary>
    /// 工单管理
    /// </summary>
    public class WorkOrderController : Controller
    {
        #region 工单工艺配置
        /// <summary>
        /// 工单管理
        /// </summary>
        public ActionResult WorkOrderMgr(string orderNo = "")
        {
            ViewBag.ProcessStatusEnum = new CommonMgr().QueryEnumTypes(typeof(ProduceStatus));
            ViewBag.Workshops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            ViewBag.OrderNo = orderNo;
            return View();
        }

        /// <summary>
        /// 查询工单列表
        /// </summary>
        public JsonResult QueryWorkOrders(int page, int limit, string workshopCode, string orderNo, string workOrderNo, ProduceStatus? status, DateTime? startDate, DateTime? endDate)
        {
            var total = 0;
            var workshopCodes = string.IsNullOrWhiteSpace(workshopCode) ? new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId).Select(_ => _.WorkshopCode).ToList() : new List<string> { workshopCode };
            var workOrders = new WorkOrderMgr().QueryWorkOrders(page, limit, out total, workshopCodes, orderNo, workOrderNo, status, startDate, endDate?.AddDays(1));
            return Json(new ResultJson<object>(workOrders, total));
        }

        /// <summary>
        /// 配置工单
        /// </summary>
        public ActionResult ConfigWorkOrder(string workOrderNo)
        {
            var workOrder = new WorkOrderMgr().GetWorkOrder(workOrderNo);
            return View(workOrder);
        }

        /// <summary>
        /// 入库核验
        /// </summary>
        public ActionResult WorkhousingVerification(int inspectId)
        {
            var inspect = new WorkOrderMgr().GetInboundInspect(inspectId);
            return View(inspect);
        }
        #endregion

        #region 分片管理
        /// <summary>
        /// 分片
        /// </summary>
        public ActionResult DistributePieces(string workOrderNo)
        {
            var workOrder = new WorkOrderMgr().GetWorkOrder(workOrderNo);
            ViewBag.OrderProduct = new OrderMgr().QueryOrderProducts(workOrder.OrderNo).FirstOrDefault(_ => string.Equals(_.ProductCode, workOrder.ProductCode, StringComparison.CurrentCultureIgnoreCase));
            ViewBag.Machines = new MachineMgr().QueryWorkshopMachines(workOrder.WorkshopCode, MachineType.WeldingMachine);
            ViewBag.EletricProduct = new AllocateOrderMgr().GetEletricProduct(workOrderNo);
            ViewBag.Colors = new ColorMgr().QueryColors(ColorType.CellColor);
            var cellParas = new CellParaMgr().QueryParas(null);
            ViewBag.CellArea = cellParas.Where(_ => _.ParaType == ParaType.CellArea).ToList();
            ViewBag.CellEfficiency = cellParas.Where(_ => _.ParaType == ParaType.CellEfficiency).ToList();
            return View(workOrder);
        }

        /// <summary>
        /// 条码分片
        /// </summary>
        [HttpPost]
        public JsonResult Distribute(VDistributeTask model, List<string> codes)
        {
            model.CreateBy = BaseEnv.UserId;
            new WorkOrderMgr().Distribute(model, codes);
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 查询分片记录
        /// </summary>
        [HttpPost]
        public JsonResult QueryDistributes(int page, int limit, string workOrderNo)
        {
            var models = new WorkOrderMgr().QueryWorkOrderDistributeTasks(workOrderNo);
            return Json(new ResultJson<List<VDistributeTaskInfo>>(models));
        }

        /// <summary>
        /// 查询分片记录
        /// </summary>
        public ActionResult DistributeCodes(int distributeTaskId)
        {
            ViewBag.DistributeTaskId = distributeTaskId;
            return View();
        }

        /// <summary>
        /// 查询分片记录
        /// </summary>
        [HttpPost]
        public JsonResult QueryDistributeCodes(int page, int limit, int distributeTaskId, DistributeCodeStatus? status, string code)
        {
            var total = 0;
            var codes = new WorkOrderMgr().QueryWorkOrderDistributeCodes(page, limit, out total, distributeTaskId, status, code);
            return Json(new ResultJson<List<VDistributeCode>>(codes, total));
        }
        #endregion

        #region 条码回收
        /// <summary>
        /// 打印/回收条码
        /// </summary>
        [HttpPost]
        public JsonResult OperateDistributeCodes(DistributeCodeOperateType operateType, List<int> codeIds, bool operateAll = true, bool forceOperate = false)
        {
            var model = new VDistributeCodeOperateTask
            {
                OperateType = operateType,
                Operator = BaseEnv.UserId,
                CreateBy = BaseEnv.UserId,
                CreateTime = DateTime.Now
            };

            model = new WorkOrderMgr().DistributeCodeOperate(model, codeIds, operateAll);

            return Json(new ResultJson<object>(new { TaskId = model.PkId }));
        }

        /// <summary>
        /// 回收条码
        /// </summary>
        public ActionResult RecycleBarCode()
        {
            ViewBag.Workshops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            return View();
        }

        /// <summary>
        /// 新增回收条码
        /// </summary>
        [HttpPost]
        public JsonResult SubmitRecycle(string barCode)
        {
            new ComponentMgr().RecycleBarCode(new VComponentRecycle
            {
                BarCode = barCode,
                CreateBy = BaseEnv.UserId
            });
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 查询回收条码列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryRecycleCompinents(int page, int limit, string workshopCode, string orderNo, string workOrderNo, string barCode)
        {
            var total = 0;
            var components = new ComponentMgr().QueryRecycleComponents(page, limit, out total, workshopCode, orderNo, workOrderNo, barCode);
            return Json(new ResultJson<object>(components, total));
        }

        /// <summary>
        /// 导出回收条码列表
        /// </summary>
        public void ExportRecycleCompinents(string workshopCode, string orderNo, string workOrderNo, string barCode)
        {
            var total = 0;
            var components = new ComponentMgr().QueryRecycleComponents(1, 0, out total, workshopCode, orderNo, workOrderNo, barCode);

            var book = new XSSFWorkbook();
            var sheet = book.CreateSheet("条码回收清单");
            for (int i = 0; i <= 8; i++)
            {
                sheet.SetColumnWidth(i, 8 * 700 + 200);
            }
            sheet.SetColumnWidth(0, 8 * 256 + 200);
            sheet.SetColumnWidth(2, 8 * 400 + 200);
            sheet.SetColumnWidth(3, 8 * 400 + 200);
            sheet.SetColumnWidth(6, 8 * 800 + 200);
            sheet.SetColumnWidth(7, 8 * 356 + 200);

            var styleCenter = book.CreateCellStyle();
            styleCenter.Alignment = HorizontalAlignment.Center;
            styleCenter.VerticalAlignment = VerticalAlignment.Center;
            styleCenter.BorderBottom = BorderStyle.Thin;
            styleCenter.BorderLeft = BorderStyle.Thin;
            styleCenter.BorderRight = BorderStyle.Thin;
            styleCenter.BorderTop = BorderStyle.Thin;

            var row1 = sheet.CreateRow(0);
            row1.Height = 30 * 20;
            row1.CreateCell(0).SetCellValue("序号");
            row1.CreateCell(1).SetCellValue("条码");
            row1.CreateCell(2).SetCellValue("车间");
            row1.CreateCell(3).SetCellValue("订单号");
            row1.CreateCell(4).SetCellValue("工单号");
            row1.CreateCell(5).SetCellValue("成品代码");
            row1.CreateCell(6).SetCellValue("成品名称");
            row1.CreateCell(7).SetCellValue("回收员");
            row1.CreateCell(8).SetCellValue("回收时间");
            for (int i = 0; i <= 8; i++)
            {
                row1.GetCell(i).CellStyle = styleCenter;
            }

            if (!components.Any())
            {
                var ms1 = new MemoryStream();
                book.Write(ms1);
                Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xlsx", $"{DateTime.Now:yyyyMMddHHmmss}条码回收清单"));
                Response.BinaryWrite(ms1.ToArray());
                book = null;
                ms1.Close();
                ms1.Dispose();
                return;
            }
            for (int i = 0; i < components.Count; i++)
            {
                var tmpRow = sheet.CreateRow(i + 1);
                tmpRow.Height = 30 * 20;
                tmpRow.CreateCell(0).SetCellValue(i + 1);
                tmpRow.CreateCell(1).SetCellValue(components[i].BarCode);
                tmpRow.CreateCell(2).SetCellValue(components[i].WorkshopName);
                tmpRow.CreateCell(3).SetCellValue(components[i].OrderNo);
                tmpRow.CreateCell(4).SetCellValue(components[i].WorkOrderNo);
                tmpRow.CreateCell(5).SetCellValue(components[i].ProductCode);
                tmpRow.CreateCell(6).SetCellValue(components[i].ProductName);
                tmpRow.CreateCell(7).SetCellValue(components[i].CNCreateBy);
                tmpRow.CreateCell(8).SetCellValue(components[i].CreateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                for (int j = 0; j <= 8; j++)
                {
                    tmpRow.GetCell(j).CellStyle = styleCenter;
                }
            }

            var ms = new MemoryStream();
            book.Write(ms);
            Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xlsx", $"{DateTime.Now:yyyyMMddHHmmss}条码回收清单"));
            Response.BinaryWrite(ms.ToArray());
            book = null;
            ms.Close();
            ms.Dispose();
            return;
        }

        /// <summary>
        /// 查询工单BOM
        /// </summary>
        [HttpPost]
        public JsonResult QueryWorkOrderBoms(string workOrderNo, SiteType siteType)
        {
            var boms = new WorkOrderMgr().QueryWorkOrderSiteBoms(workOrderNo, siteType);
            return Json(new { ErrCode = 200, Data = boms });
        }
        #endregion

        #region 打包管理
        /// <summary>
        /// 打包管理页面
        /// </summary>
        public ActionResult PackMgr()
        {
            ViewBag.Workshops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            ViewBag.PackStatusEnum = new CommonMgr().QueryEnumTypes(typeof(PackStatus));
            ViewBag.PackInspectStatusEnum = new CommonMgr().QueryEnumTypes(typeof(PackInboundInspectStatus));
            return View();
        }

        /// <summary>
        /// 统一打包
        /// </summary>
        public ActionResult UnionPack(string packNo = "")
        {
            ViewBag.WorkShops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            var pack = string.IsNullOrWhiteSpace(packNo) ? null : new WorkOrderMgr().GetPack(packNo);
            ViewBag.ActualName = (pack == null ? BaseEnv.User : new UserMgr().GetUser(pack.CreateBy))?.TrueName;
            return View(pack);
        }

        /// <summary>
        /// 查询未完成的包装
        /// </summary>
        [HttpPost]
        public JsonResult QueryUnFinishedPacks(string workshopCode)
        {
            var packs = new WorkOrderMgr().QueryUnFinishedPacks(workshopCode);
            return Json(new
            {
                ErrCode = 200,
                Data = packs.Select(_ => new
                {
                    _.PackNo,
                    _.PackIndex
                }).ToList()
            });
        }

        /// <summary>
        /// 统一打包单页
        /// </summary>
        public ActionResult Packing(string workshopCode, bool isNewPack = false, string packNo = "", string barCode = "")
        {
            ViewBag.WorkshopCode = workshopCode;
            ViewBag.BarCode = barCode;
            ViewBag.PackNo = packNo;
            var pack = string.IsNullOrWhiteSpace(packNo) || isNewPack ? null : new WorkOrderMgr().GetPack(packNo);
            ViewBag.User = pack == null ? BaseEnv.User : new UserMgr().GetUser(pack.CreateBy);
            return View(pack);
        }

        /// <summary>
        /// 打包页
        /// </summary>
        public ActionResult PackEdit(string packNo = "")
        {
            ViewBag.WorkShops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            var pack = string.IsNullOrWhiteSpace(packNo) ? null : new WorkOrderMgr().GetPack(packNo);
            ViewBag.User = pack == null ? BaseEnv.User : new UserMgr().GetUser(pack.CreateBy);
            return View(pack);
        }

        /// <summary>
        /// 查询打包列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryPacks(int page, int limit, string workshopCode, string orderNo, string workOrderNo, string packBatchNo, string packNo, DateTime startDate, DateTime endDate, PackStatus? packStatus, PackInboundInspectStatus? inspectStatus)
        {
            var workshopCodes = !string.IsNullOrWhiteSpace(workshopCode) ? new List<string> { workshopCode } : new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId).Select(_ => _.WorkshopCode).Distinct().ToList();
            var total = 0;
            var packs = new WorkOrderMgr().QueryPacks(page, limit, out total, workshopCodes, orderNo, workOrderNo, packBatchNo, packNo, startDate, endDate, packStatus, inspectStatus);

            return Json(new { ErrCode = 200, Data = packs, TotalCount = total });
        }

        /// <summary>
        /// 打包
        /// </summary>
        [HttpPost]
        public JsonResult CreatePack(VPack model, string barCode = "")
        {
            model.CreateBy = BaseEnv.UserId;
            var pack = new WorkOrderMgr().CreatePack(model);
            return Json(new { ErrCode = 200, Data = pack });
        }

        /// <summary>
        /// 打包组件
        /// </summary>
        [HttpPost]
        public JsonResult PackProduct(string workshopCode, string barCode)
        {
            var pack = new WorkOrderMgr().PackProduct(new VPackProduct { BarCode = barCode.ToUpper(), WorkshopCode = workshopCode, CreateBy = BaseEnv.UserId });
            return Json(new { ErrCode = 200, Data = pack });
        }

        /// <summary>
        /// 明确包装打包组件
        /// </summary>
        [HttpPost]
        public JsonResult ActualPackProduct(string packNo, string barCode)
        {
            VPackCondition packCondition = null;
            VPackProduct packs = null;

            new WorkOrderMgr().PackProduct(new VPackProduct { PackNo = packNo.ToUpper(), BarCode = barCode.ToUpper(), CreateBy = BaseEnv.UserId }, out packCondition, out packs);
            return Json(new { ErrCode = 200, Data = (packCondition) });
        }

        /// <summary>
        /// 解包组件
        /// </summary>
        [HttpPost]
        public JsonResult UnPackProduct(string barCode)
        {
            new WorkOrderMgr().UnPackProduct(new VPackProduct { BarCode = barCode, ModifyBy = BaseEnv.UserId });
            return Json(new { ErrCode = 200 });
        }

        /// <summary>
        /// 完成打包
        /// </summary>
        [HttpPost]
        public JsonResult FinishPack(string packNo)
        {
            new WorkOrderMgr().FinishPack(new VPack { PackNo = packNo, ModifyBy = BaseEnv.UserId });
            return Json(new { ErrCode = 200 });
        }

        /// <summary>
        /// 解包
        /// </summary>
        [HttpPost]
        public JsonResult UnPack(string packNo)
        {
            new WorkOrderMgr().UnPack(new VPack { PackNo = packNo, ModifyBy = BaseEnv.UserId });
            return Json(new { ErrCode = 200 });
        }

        /// <summary>
        /// 更换打包编号
        /// </summary>
        [HttpPost]
        public JsonResult ChangePackNo(string packNo, string newPackNo)
        {
            new WorkOrderMgr().ChangePackNo(new VPack { PackNo = packNo, ModifyBy = BaseEnv.UserId }, newPackNo);
            return Json(new { ErrCode = 200 });
        }

        /// <summary>
        /// 更换打包组件
        /// </summary>
        [HttpPost]
        public JsonResult ExchangePackProduct(string packNo, string barCode, string newBarCode)
        {
            new WorkOrderMgr().ExchangePackProduct(new VPackProduct
            {
                PackNo = packNo.Trim(),
                BarCode = barCode.Trim(),
                ModifyBy = BaseEnv.UserId
            }, newBarCode.ToUpper().Trim());
            return Json(new { ErrCode = 200 });
        }
        #endregion

        #region 入库检
        /// <summary>
        /// 入库检管理
        /// </summary>
        public ActionResult InboundInspect()
        {
            ViewBag.Workshops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            ViewBag.InspectStatuses = new CommonMgr().QueryEnumTypes(typeof(PackInboundInspectStatus));
            return View();
        }

        /// <summary>
        /// 入库检
        /// </summary>
        public ActionResult EditInboundInspect(string packNo = "")
        {
            ViewBag.PackNo = packNo;
            ViewBag.PackInboundInspectStatusEnums = new CommonMgr().QueryEnumTypes(typeof(PackInboundInspectStatus)).Where(_ => _.Key > 0).ToList();
            return View();
        }

        /// <summary>
        /// 查询打包
        /// </summary>
        [HttpPost]
        public JsonResult GetPackInspect(string packNo)
        {
            var pack = new WorkOrderMgr().GetInboundInspect(packNo);
            return Json(new { ErrCode = 200, Data = pack });
        }

        /// <summary>
        /// 查询入库检列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryInboundInspects(int page, int limit, string workshopCode, string orderNo, string workOrderNo, string packBatchNo, string packNo, DateTime startTime, DateTime endTime, PackInboundInspectStatus? inspectStatus)
        {
            var workshopCodes = !string.IsNullOrWhiteSpace(workshopCode) ? new List<string> { workshopCode } : new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId).Select(_ => _.WorkshopCode).Distinct().ToList();
            var total = 0;
            var inspects = new WorkOrderMgr().QueryInboundInspectPacks(page, limit, out total, workshopCodes, orderNo, workOrderNo, packBatchNo, packNo, startTime, endTime, inspectStatus);

            return Json(new { ErrCode = 200, Data = inspects, TotalCount = total });
        }

        /// <summary>
        /// 获取检核产品列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryInspectProducts(int page, int limit, int inspectId)
        {
            var products = new WorkOrderMgr().QueryInspectProducts(inspectId);
            return Json(new { ErrCode = 200, Data = products, TotalCount = products.Count });
        }

        /// <summary>
        /// 提交入库检
        /// </summary>
        [HttpPost]
        public JsonResult SaveVerification(VInboundInspect model)
        {
            try
            {
                model.InspectBy = BaseEnv.UserId;
                model.ModifyBy = BaseEnv.UserId;
                new WorkOrderMgr().Verification(model);

                return Json(new { ErrCode = 200 });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    ErrCode = 500,
                    ErrMsg = ex.Message
                });
            }
        }
        #endregion

        #region 工单结转

        /// <summary>
        /// 工单结转列表
        /// </summary>
        public ActionResult CarryOverMgr()
        {
            ViewBag.WorkShops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            ViewBag.CarryOverStatusEnums = new CommonMgr().QueryEnumTypes(typeof(CarryOverOrderStatus));

            return View();
        }

        /// <summary>
        /// 结转详情/编辑
        /// </summary>
        public ActionResult CarryOverDetail(int pkId, int isReadonly)
        {
            ViewBag.IsReadonly = isReadonly;
            var carryOverOrder = new CarryOverOderMgr().GetCarryOverOrder(pkId);

            return View(carryOverOrder);
        }

        /// <summary>
        /// 查询结转工单
        /// </summary>
        [HttpPost]
        public JsonResult QueryWorkOrderList(int page, int limit, string workshopCode, string fromWorkOrderNo, string toToWorkOrderNo, string createdTimeRange, CarryOverOrderStatus? status)
        {
            var data = new CarryOverOderMgr().QueryCarryOverOrders(BaseEnv.UserId, page, limit, workshopCode, fromWorkOrderNo, toToWorkOrderNo, createdTimeRange, status);

            return Json(new ResultJson<List<VCarryOverOrder>>(data.Item1, data.Item2));
        }

        /// <summary>
        /// 创建结转工单
        /// </summary>
        [HttpPost]
        public JsonResult CreateCarryOverOder(VCarryOverOrder model)
        {
            model.CreateBy = BaseEnv.UserId;
            model.CreateTime = DateTime.Now;

            var entity = new CarryOverOderMgr().CreateCarryOverOrder(model);

            return Json(new ResultJson<VCarryOverOrder>(entity));
        }

        /// <summary>
        /// 确认结转
        /// </summary>
        [HttpPost]
        public JsonResult CarryOver(string carryOverNo)
        {
            new CarryOverOderMgr().CompleteCarryOver(new VCarryOverOrder
            {
                CarryOverNo = carryOverNo,
                ModifyBy = BaseEnv.UserId
            });

            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 废弃
        /// </summary>
        [HttpPost]
        public JsonResult DeleteCarryOverOrder(string carryOverNo)
        {
            new CarryOverOderMgr().DeleteCarryOverOrder(new VCarryOverOrder { CarryOverNo = carryOverNo, ModifyBy = BaseEnv.UserId });

            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 查询结转物料
        /// </summary>
        [HttpPost]
        public JsonResult QueryCarryOverProducts(string carryOverNo)
        {
            var data = new CarryOverOderMgr().QueryCarryOverProducts(carryOverNo);

            return Json(new ResultJson<List<VCarryOverProduct>>(data));
        }

        /// <summary>
        /// 保存结转物料
        /// </summary>
        [HttpPost]
        public JsonResult SaveCarryOverProducts(string carryOverNo, List<VCarryOverProduct> products)
        {
            new CarryOverOderMgr().SaveCarryOverProducts(new VCarryOverOrder
            {
                CarryOverNo = carryOverNo,
                ModifyBy = BaseEnv.UserId
            }, products ?? new List<VCarryOverProduct>());

            return Json(new ResultJson<object>());
        }

        #endregion

        #region 车间补片
        /// <summary>
        /// 补片管理
        /// </summary>
        public ActionResult CompenCellMgr()
        {
            ViewBag.FragmentTypes = new CommonMgr().QueryEnumTypes(typeof(FragmentType));
            ViewBag.CompenProcessTypes = new CommonMgr().QueryEnumTypes(typeof(CompenProcessType));
            var workshops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            ViewBag.Workshops = workshops;
            ViewBag.WorkOrderNos = (!workshops.Any() ? new List<VWorkOrder>()
                : new WorkOrderMgr().QueryWorkOrders(workshops.FirstOrDefault().WorkshopCode)).OrderByDescending(_ => _.PkId).Select(_ => _.WorkOrderNo).Distinct().ToList();
            return View();
        }

        /// <summary>
        /// 查询补片记录
        /// </summary>
        [HttpPost]
        public JsonResult QueryCompenCellRecords(int page, int limit, string workshopCode, string workOrderNo,
            CompenProcessType? process, FragmentType? reason, DateTime startTime, DateTime endTime)
        {
            var result = new WorkOrderMgr().QueryCompenCellRecords(page, limit, workshopCode, workOrderNo, process, reason, startTime, endTime);
            return Json(new ResultJson<object>(result.Item2, result.Item1));
        }

        /// <summary>
        /// 补片页面
        /// </summary>
        public ActionResult CompenCell()
        {
            ViewBag.User = BaseEnv.User;
            ViewBag.FragmentTypes = new CommonMgr().QueryEnumTypes(typeof(FragmentType));
            ViewBag.CompenProcessTypes = new CommonMgr().QueryEnumTypes(typeof(CompenProcessType));
            var workshops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            ViewBag.Workshops = workshops;
            ViewBag.Duties = new WorkshopDutyMgr().QueryDuties(workshops.FirstOrDefault().WorkshopCode);
            ViewBag.WorkOrderNos = (!workshops.Any() ? new List<VWorkOrder>()
                : new WorkOrderMgr().QueryWorkOrders(workshops.FirstOrDefault().WorkshopCode)).OrderByDescending(_ => _.PkId).Select(_ => _.WorkOrderNo).Distinct().ToList();
            ViewBag.Cells = new ProductMgr().QueryProducts("电池片").Select(_ => _.ProductCode).Distinct().ToList();

            return View();
        }

        /// <summary>
        /// 查询车间工单
        /// </summary>
        [HttpPost]
        public JsonResult QueryWorkshopWorkOrderNos(string workshopCode)
        {
            var workOrderNos = string.IsNullOrWhiteSpace(workshopCode) ? new List<string>()
                : new WorkOrderMgr().QueryWorkOrders(workshopCode).OrderByDescending(_ => _.PkId).Select(_ => _.WorkOrderNo).Distinct().ToList();
            return Json(new ResultJson<object>(workOrderNos));
        }

        /// <summary>
        /// 查询车间班次
        /// </summary>
        [HttpPost]
        public JsonResult QueryWorkshopDuties(string workshopCode)
        {
            var duties = new WorkshopDutyMgr().QueryDuties(workshopCode);
            return Json(new ResultJson<object>(duties));
        }

        /// <summary>
        /// 查询工单电池片
        /// </summary>
        [HttpPost]
        public JsonResult QueryWorkOrderCells(string workOrderNo)
        {
            var cells = new AllocateOrderMgr().QueryWorkOrderCells(workOrderNo);
            return Json(new ResultJson<object>(cells));
        }

        /// <summary>
        /// 执行补片
        /// </summary>
        [HttpPost]
        public JsonResult DoCompenCell(VCompenCellRecord model)
        {
            model.CreateBy = BaseEnv.UserId;
            new WorkOrderMgr().CompenCell(model);
            return Json(new ResultJson<object>());
        }
        #endregion

        #region 车间发料
        /// <summary>
        /// 发料管理
        /// </summary>
        public ActionResult MaterialBillMgr()
        {
            ViewBag.Workshops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            return View();
        }

        /// <summary>
        /// 新建发料
        /// </summary>
        public ActionResult IssueMaterialEdit()
        {
            ViewBag.Workshops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            return View();
        }

        /// <summary>
        /// 单据详情页
        /// </summary>
        public ActionResult MaterialBillDetail(string billNo)
        {
            var bill = new LineMaterialMgr().GetBill(billNo);
            return View(bill);
        }

        /// <summary>
        /// 查询物料单
        /// </summary>
        [HttpPost]
        public JsonResult QueryLineMaterialBills(int page, int limit, string workshopCode, int lineId, string workOrderNo, LineMaterialBillType? billType)
        {
            var workshopCodes = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId)
                .Where(_ => string.IsNullOrWhiteSpace(workshopCode) ? true : StringUtils.Equals(workshopCode, _.WorkshopCode))
                .Select(_ => _.WorkshopCode).Distinct().ToList();
            var result = new LineMaterialMgr().QueryBills(page, limit, workshopCodes, lineId, workOrderNo, billType);
            return Json(new ResultJson<object>(result.Item2, result.Item1));
        }

        /// <summary>
        /// 查询工单调拨单托盘号和箱号
        /// </summary>
        [HttpPost]
        public JsonResult QueryWorkOrderAllocateNos(string workOrderNo)
        {
            var allocateProducts = new AllocateOrderMgr().QueryWorkOrderAllocateProducts(workOrderNo);
            var batchNoBigs = allocateProducts.Select(_ => _.BatchNoBig).Distinct().Where(_ => !string.IsNullOrWhiteSpace(_)).ToList();
            var batchNoSmalls = allocateProducts.Select(_ => _.BatchNoSmall).Distinct().Where(_ => !string.IsNullOrWhiteSpace(_)).ToList();
            return Json(new ResultJson<object>(new { batchNoBigs, batchNoSmalls }));
        }

        /// <summary>
        /// 查询工单调拨单产品
        /// </summary>
        [HttpPost]
        public JsonResult QueryWorkOrderAllocateProducts(string workOrderNo, string batchNoBig, string batchNoSmall)
        {
            if (string.IsNullOrWhiteSpace(workOrderNo) || string.IsNullOrWhiteSpace(batchNoBig) && string.IsNullOrWhiteSpace(batchNoSmall))
            {
                return Json(new ResultJson<object>(new List<VAllocateProduct>()));
            }
            var allocateProducts = new AllocateOrderMgr().QueryWorkOrderAllocateProducts(workOrderNo);
            if (!string.IsNullOrWhiteSpace(batchNoSmall))
            {
                allocateProducts = allocateProducts.Where(_ => StringUtils.Equals(_.BatchNoSmall, batchNoSmall)).ToList();
            }
            else
            {
                allocateProducts = allocateProducts.Where(_ => StringUtils.Equals(_.BatchNoBig, batchNoBig)).ToList();
            }
            return Json(new ResultJson<object>(allocateProducts));
        }

        /// <summary>
        /// 保存物料单据
        /// </summary>
        [HttpPost]
        public JsonResult SaveLineMaterialBill(VLineMaterialBill model)
        {
            model.CreateBy = BaseEnv.UserId;
            new LineMaterialMgr().SaveLineMaterialBill(model);
            return Json(new ResultJson<object>());
        }
        #endregion

        #region 产线退料
        /// <summary>
        /// 新建退料
        /// </summary>
        public ActionResult ReturnMaterialEdit()
        {
            ViewBag.Workshops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            return View();
        }
        #endregion

        #region 产线库存
        /// <summary>
        /// 产线库存
        /// </summary>
        public ActionResult LineStorageMgr()
        {
            ViewBag.Workshops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            return View();
        }

        /// <summary>
        /// 查询产线库存
        /// </summary>
        [HttpPost]
        public JsonResult QueryLineStoragess(int page, int limit, string workshopCode, int lineId, string workOrderNo, bool? hasStorage, string billNo)
        {
            workshopCode = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId)
                .FirstOrDefault(_ => string.IsNullOrWhiteSpace(workshopCode) ? false : StringUtils.Equals(workshopCode, _.WorkshopCode))?.WorkshopCode;
            if (string.IsNullOrWhiteSpace(workshopCode))
            {
                return Json(new ResultJson<object>(new List<object>(), 0));
            }

            var result = new LineMaterialMgr().QueryLineStoragess(page, limit, workshopCode, lineId, workOrderNo, hasStorage, billNo);
            return Json(new ResultJson<object>(result.Item2, result.Item1));
        }
        #endregion
    }
}
